package com.xsz.pda.net.udp

import android.util.Log
import com.alibaba.fastjson.JSON
import com.xsz.pda.AppExecutors
import com.xsz.pda.api.beans.ApiCheckRecord
import com.xsz.pda.net.Constant
import java.io.IOException
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress


class UDPHelper {
    private val TAG = "UDPHelper"
    private val PORT = 6789
    private val TIMEOUT = 2000 // 超时 2 seconds
    private val MAX_TRIES = 3 // 重试 2 次 保证消息的可靠性
    private val udpServer= UdpServer("0.0.0.0", PORT)
    private val updListener = Thread(udpServer,"UDPListener")
    // 发送给局域网
    private val broadcastAddress: InetAddress = InetAddress.getByName("255.255.255.255")

    private fun sendMessage(msg: String) {
       AppExecutors.networkIO.execute {
           DatagramSocket().use { socket ->
               val data = msg.toByteArray()
               socket.broadcast = true
               socket.soTimeout = TIMEOUT
               val packet = DatagramPacket(data, data.size, broadcastAddress, PORT)
               for (i in 1..MAX_TRIES) {
//                   Log.d(TAG, "Sending message to " + broadcastAddress.hostAddress!! + " (attempt " + i.toString() + ")")
                   try {
                       socket.send(packet)
                   }catch (e:IOException){
                       Log.i(TAG, "发送消息异常 ", e)
                   }
               }
           }
       }
    }

    fun syncRecord(syncTicketItem: ApiCheckRecord){
        val map: MutableMap<String, Any> = HashMap()
        map["what"] = Constant.SYNC_CHECK_RECORD
        map["data"] = syncTicketItem
        sendMessage( JSON.toJSONString(map))
        Log.d(TAG, "已发送局域网验票记录同步！")
    }


    fun start(){
        updListener.start()
    }

    fun stop(){
        udpServer.stop()
        updListener.interrupt()
    }

    fun setMsgListener(what: Int, msgListener: OnMsgCallback) {
        udpServer.setMsgListener(what, msgListener)
    }

}